import { asyncRoutes, constantRoutes } from '@/router';
import { getRouterItem } from '@/utils/storage';

/**
 * 使用meta.id确定当前用户是否具有权限
 * @param routerId
 * @param route
 */
function hasPermission(routerId, route) {
  if (route.meta && route.meta.id) {
    return routerId.some((role) => route.meta.id.includes(role));
  } else {
    return true;
  }
}

/**
 * 通过递归过滤异步路由表  meta:{
 *   id:'当前路由的路径',
 *
 * }
 * @param routes asyncRoutes
 * @param router_id
 */
export function filterAsyncRoutes(routes, router_id) {
  const res = [];
  routes.forEach((route) => {
    const tmp = { ...route };
    if (hasPermission(router_id, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, router_id);
      }
      res.push(tmp);
    }
  });
  return res;
}

const state = {
  routes: [],
  addRoutes: [],
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
  },
};

const actions = {
  // rootState: for modules/users filter router id
  generateRoutes({ commit, rootState }, roles) {
    return new Promise((resolve) => {
      // let {router_id} = rootState.user;
      const router_id = getRouterItem();
      // let accessedRoutes;
      // if (roles.includes('admin')) {
      //   accessedRoutes = asyncRoutes || []
      // } else {
      //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // }
      const filterRouter = filterAsyncRoutes(asyncRoutes, router_id);
      commit('SET_ROUTES', filterRouter);
      resolve(filterRouter);
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
